package com.boyan.auth.interceptor;

import com.boyan.utils.CurrentHolder;
import com.boyan.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        StringBuffer url = request.getRequestURL();
        log.info("拦截到请求: {}", url);


        if(url.toString().contains("/login")){
            log.info("登录请求,放行");
            return true;
        }

        if(url.toString().contains("/doc.html")){
            log.info("接口文档请求,放行");
            return true;
        }



        String token = request.getHeader("token");
        log.info("获取到的令牌: {}", token);

        if(token==null || token.isEmpty()){
            log.info("令牌为空, 响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("text/plain;charset=UTF-8"); // 新增内容类型设置
            response.getWriter().write("令牌为空"); // 新增响应内容
            return false;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer userId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(userId);
            log.info("token验证通过,放行");
            log.info("当前登录员工ID: {}, 将其存入ThreadLocal", userId);
        } catch (Exception e) {
            log.info("令牌非法, 响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6. 校验通过, 放行
        log.info("令牌合法, 放行");


        //7. 删除ThreadLocal中的数据
        CurrentHolder.remove();

        return true;

    }
}
